class ChatManager {
    constructor() {
        this.username = '';
        this.currentServer = window.location.origin;
        this.selectedUser = null;
        this.isPrivateChat = window.targetUser ? true : false;
        this.targetUser = window.targetUser || null;
        this.currentPage = 1;
        this.isLoadingMessages = false;
        this.userScrolled = false;
        this.lastScrollPosition = 0;
        this.lastUserListUpdate = 0;
        this.userListUpdateInterval = 5000; // 5秒更新一次
        this.cachedUserList = new Set();
        
        this.initializeChat();
        this.checkPrivateChatStatus();
    }

    initializeChat() {
        this.setupEventListeners();
        this.startPeriodicUpdates();
        this.loadUsername();
    }

    loadUsername() {
        const savedUsername = localStorage.getItem('chatUsername');
        if (savedUsername) {
            this.username = savedUsername;
            document.getElementById('username').value = savedUsername;
        }
    }

    setupEventListeners() {
        const messageInput = document.getElementById('message-input');
        const messagesContainer = document.getElementById('messages-container');
        const usernameInput = document.getElementById('username');
        const sendButton = document.querySelector('.send-btn');

        messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });

        messageInput.addEventListener('input', () => {
            messageInput.style.height = '45px';
            const newHeight = Math.min(messageInput.scrollHeight, 150);
            messageInput.style.height = newHeight + 'px';

            sendButton.disabled = !messageInput.value.trim();
        });

        sendButton.disabled = !messageInput.value.trim();

        messagesContainer.addEventListener('scroll', (e) => {
            this.handleScroll(e);
        });

        usernameInput.addEventListener('change', (e) => {
            this.username = e.target.value.trim();
            localStorage.setItem('chatUsername', this.username);
        });

        sendButton.addEventListener('click', () => {
            this.sendMessage();
        });
    }

    handleScroll(e) {
        const container = e.target;
        this.userScrolled = true;
        this.lastScrollPosition = container.scrollTop;
    }

    startPeriodicUpdates() {
        setInterval(() => this.updateMessages(), 1000);
        
        setInterval(() => {
            if (document.visibilityState === 'visible') {
                this.updateUserList();
            }
        }, this.userListUpdateInterval);

        document.addEventListener('visibilitychange', () => {
            if (document.visibilityState === 'visible') {
                this.updateUserList();
            }
        });
    }

    async updateMessages(loadMore = false) {
        if (this.isLoadingMessages) return;
        this.isLoadingMessages = true;

        try {
            const endpoint = this.isPrivateChat ? 
                `/get_private_messages/${this.targetUser}` : 
                '/get_messages';
            
            const response = await fetch(`${this.currentServer}${endpoint}?username=${encodeURIComponent(this.username)}&page=${this.currentPage}`);
            const data = await response.json();
            
            if (data.error) {
                console.error('获取消息失败:', data.error);
                return;
            }
            
            this.renderMessages(data.messages, loadMore);
            
            if (!loadMore && !this.userScrolled) {
                this.scrollToBottom();
            }
        } catch (error) {
            console.error('更新消息失败:', error);
        } finally {
            this.isLoadingMessages = false;
        }
    }

    renderMessages(messages, loadMore = false) {
        const container = document.getElementById('messages-container');
        
        if (!loadMore) {
            container.innerHTML = '<div class="load-more"><button onclick="chatManager.loadMoreMessages()">加载更多消息</button></div>';
        }

        messages.forEach(msg => {
            const messageDiv = this.renderMessage(msg);
            if (loadMore) {
                container.insertBefore(messageDiv, container.firstChild.nextSibling);
            } else {
                container.appendChild(messageDiv);
            }
        });
    }

    renderMessage(message) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message-bubble ${
            message.username === this.username ? 'message-right' : 'message-left'
        }`;
        
        if (message.is_file) {
            messageDiv.innerHTML = this.renderFileMessage(message);
        } else {
            messageDiv.innerHTML = this.renderTextMessage(message);
        }
        
        return messageDiv;
    }

    renderTextMessage(message) {
        return `
            <div class="message-header">
                <span class="username">${message.username}</span>
                <span class="timestamp">${message.timestamp}</span>
            </div>
            <div class="message-content">${message.message}</div>
        `;
    }

    renderFileMessage(message) {
        return `
            <div class="message-header">
                <span class="username">${message.username}</span>
                <span class="timestamp">${message.timestamp}</span>
            </div>
            <div class="message-content">
                <div class="file-message">
                    <svg width="24" height="24" viewBox="0 0 24 24">
                        <path fill="currentColor" d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/>
                    </svg>
                    ${message.message}
                    <a href="/download_file/${message.filename}" target="_blank">下载文件</a>
                </div>
            </div>
        `;
    }

    async sendMessage() {
        const input = document.getElementById('message-input');
        const message = input.value.trim();
        const sendButton = document.querySelector('.send-btn');
        
        if (!message) return;

        try {
            sendButton.disabled = true;

            const response = await fetch(`${this.currentServer}/send_message`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: this.username || `用户(${await this.getClientIP()})`,
                    message: message,
                    to_user: this.isPrivateChat ? this.targetUser : null
                })
            });

            const data = await response.json();
            if (data.error) {
                alert(data.error);
                return;
            }

            if (response.ok) {
                input.value = '';
                input.style.height = '45px';
                this.userScrolled = false;
                this.updateMessages();
                
                input.focus();
                sendButton.disabled = true;
            }
        } catch (error) {
            console.error('发送消息失败:', error);
            alert('发送消息失败，请重试');
        } finally {
            sendButton.disabled = false;
        }
    }

    async updateUserList() {
        const now = Date.now();
        if (now - this.lastUserListUpdate < this.userListUpdateInterval) {
            return;
        }

        try {
            const response = await fetch(
                `${this.currentServer}/get_online_users?username=${encodeURIComponent(this.username || '')}`
            );
            const users = await response.json();
            
            const newUserSet = new Set(users);
            if (this.areUserListsEqual(this.cachedUserList, newUserSet)) {
                return;
            }
            
            this.cachedUserList = newUserSet;
            this.lastUserListUpdate = now;

            const userList = document.getElementById('user-list');
            if (!userList) return;

            userList.innerHTML = `
                <div class="user-item ${!this.selectedUser ? 'selected' : ''}" 
                     onclick="chatManager.selectUser(null)">
                    公共聊天
                </div>
            `;
            
            users.forEach(user => {
                if (user !== this.username) {
                    userList.innerHTML += `
                        <div class="user-item ${this.selectedUser === user ? 'selected' : ''}"
                             onclick="chatManager.selectUser('${user}')">
                            ${user}
                            ${this.isUserActive(user) ? '<span class="online-indicator"></span>' : ''}
                        </div>
                    `;
                }
            });
        } catch (error) {
            console.error('更新用户列表失败:', error);
        }
    }

    areUserListsEqual(setA, setB) {
        if (setA.size !== setB.size) return false;
        for (const item of setA) {
            if (!setB.has(item)) return false;
        }
        return true;
    }

    isUserActive(user) {
        // 这里可以添加用户活跃状态的判断逻辑
        return true;
    }

    selectUser(user) {
        if (user) {
            window.location.href = `/private_chat/${user}`;
        } else {
            window.location.href = '/';
        }
    }

    scrollToBottom() {
        const container = document.getElementById('messages-container');
        container.scrollTop = container.scrollHeight;
    }

    loadMoreMessages() {
        this.currentPage++;
        this.updateMessages(true);
    }

    checkPrivateChatStatus() {
        if (this.isPrivateChat && !this.username) {
            const username = prompt('请输入您的用户名以开始私聊');
            if (username) {
                this.username = username;
                localStorage.setItem('chatUsername', username);
                document.getElementById('username').value = username;
            } else {
                window.location.href = '/';
            }
        }
    }

    async getClientIP() {
        try {
            const response = await fetch(`${this.currentServer}/get_client_ip`);
            const data = await response.json();
            return data.ip;
        } catch (error) {
            console.error('获取IP失败:', error);
            return 'unknown';
        }
    }
}

// 初始化聊天管理器
const chatManager = new ChatManager(); 